// pages/form/form.js
const app = getApp()
const db = wx.cloud.database()
const upload = app.require("lib/upload")
const to = app.require("lib/awaitTo")
Page({
	mixins: [require("./mixins/topic")],
	data: {
		user: wx.getStorageSync('user'),
		form: {
			title: "",
			topic: "",
			content: "",
			imgList: []
		}
	},
	onLoad(options) {

	},
	chooseImg() {
		wx.chooseImage({
			count: 9 - this.data.form.imgList.length,
			sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album', 'camera'], //从相册选择
			success: (res) => {
				if (this.data.form.imgList.length != 0) {
					this.setData({ "form.imgList": this.data.form.imgList.concat(res.tempFilePaths) })
				} else {
					this.setData({ "form.imgList": res.tempFilePaths })
				}
			}
		});
	},
	async delImg(e) {
		const index = e.currentTarget.dataset.index
		const temp = this.data.form.imgList
		temp.splice(index, 1)
		this.setData({ "form.imgList": temp })
	},
	chooseTopic(e) {
		this.setData({ "form.topic": e.currentTarget.dataset.label, "topic.flag": false })
	},
	titleInput(e) {
		this.setData({ "form.title": e.detail.value })
	},
	contentInput(e) {
		this.setData({ "form.content": e.detail.value })
	},
	async submit() {
		wx.showLoading({
			mask: true,
			title: "发布中"
		})
		const imgList = []
		for (let img of this.data.form.imgList) {
			const uploadRes = await upload(img)
			imgList.push(uploadRes.fileID)
		}
		const form = {
			userId: this.data.user._id,
			...this.data.form,
			imgList,
			createTime: new Date().getTime(),
			user: {
				nickName: this.data.user.nickName,
				avatarUrl: this.data.user.avatarUrl
			},
			favor: [],
			collection: [],
			favorNum: 0,
			collectionNum: 0,
			viewNum: 0,
			createTime: new Date().getTime()
		}
		const [err] = await to(db.collection("post").add({
			data: form
		}))
		if (err) {
			return
		}
		wx.hideLoading()
		const pages = getCurrentPages()
		const lastPage = pages[pages.length - 2]
		lastPage.onPullDownRefresh()
		wx.navigateBack()
	}
})